"""
    Created By Khun on 2020/4/11
"""

__author__ = 'Khun'

from flask import request, redirect, render_template, flash, url_for, g
from flask_login import login_user, logout_user, login_required, current_user

from app.vipadmin import vipadmin
from app.forms.user import LoginForm
from app.models import User


@vipadmin.before_app_request
def before_request():
    try:
        g.user = current_user
    except Exception as e:
        pass


@vipadmin.route('/login', methods=['GET', 'POST'])
def login():
    """ 登录 """

    form = LoginForm()
    if request.method == 'POST' and form.validate():
        user = User.query.filter_by(username=form.username.data).first()
        if user and user.check_password(form.password.data):
            login_user(user, remember=True)
            return redirect(request.args.get('next') or url_for('vipadmin.index'))
        else:
            flash('用户名或者密码不正确', 'danger')
    return render_template('login.html', form=form)


@vipadmin.route('/logout')
@login_required
def logout():
    logout_user()
    return redirect(url_for('vipadmin.login'))
